#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_001.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_001.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test1.c <<EOF
#include <stdio.h>
#include <string.h>
#include <nettle/aes.h>

int main()
{
    struct aes128_ctx ctx;
    // AES-128密钥
    const uint8_t key[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
                             0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
    // 待加密的明文
    const uint8_t plaintext[16] = "hello, nettle!";
    uint8_t ciphertext[16];
    uint8_t decrypted[16];
    
    // 初始化密钥
    aes128_set_encrypt_key(&ctx, key);
    // 加密
    aes128_encrypt(&ctx, AES_BLOCK_SIZE, ciphertext, plaintext);

    printf("加密后的密文: ");
    for (size_t i = 0; i < AES_BLOCK_SIZE; i++) {
        printf("%02x", ciphertext[i]);
    }
    printf("\\n");

    // 使用相同的密钥初始化上下文进行解密
    aes128_set_decrypt_key(&ctx, key);
    // 解密
    aes128_decrypt(&ctx, AES_BLOCK_SIZE, decrypted, ciphertext);

    // 检测原文和解密后的文本是否匹配
    if (memcmp(plaintext, decrypted, AES_BLOCK_SIZE) == 0) {
        printf("解密成功: 解密后的文本与原始明文匹配.\\n");
    } else {
        printf("解密失败: 解密后的文本与原始明文不匹配.\\n");
    }

    return 0;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test1 nettle_test1.c -lnettle')
        code, nettle_result = self.cmd("./nettle_test1")
        self.assertIn('解密成功: 解密后的文本与原始明文匹配', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test1 nettle_test1.c')
